package com.zx.Ding.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.Ding.common.R;
import com.zx.Ding.dto.DishDto;
import com.zx.Ding.entity.Category;
import com.zx.Ding.entity.Dish;
import com.zx.Ding.entity.DishFlavor;
import com.zx.Ding.entity.Setmeal;
import com.zx.Ding.service.CategoryService;
import com.zx.Ding.service.DishFlavorService;
import com.zx.Ding.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page> Page(int page, int pageSize, String name, String cName) {

        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Dish::getCategoryId).orderByAsc(Dish::getSort).like(name != null, Dish::getName, name);
        dishService.page(pageInfo, queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //店铺名和商品名查询
            LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(categoryId != null, Category::getId, categoryId).like(cName != null, Category::getName, cName);
            /* Category category = category Service.getById(categoryId);*/
            Category category = categoryService.getOne(wrapper);
            if (category == null) {
                return null;
            }
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        if (cName != null && cName != "") {
            dishDtoPage.setTotal(list.size());
        }
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> sava(@RequestBody DishDto dishDto, HttpServletRequest request) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //请理缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        //请理修改的分类的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        request.setAttribute("aa", 1);
        return R.success("新增成功");
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //请理所有的菜品的缓存数据
       /* Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        //请理修改的分类的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    /**
     * 根据菜品查询对应的菜品数据
     *
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>>list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //查询条件为起售状态的
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        //将结果返回给前端*
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish,String name) {
        System.out.println("--------"+name);
        List<DishDto> dtoList = null;
        //根据分类ID构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //1.先从redis中获取缓存数据
        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //2.如果存在就直接返回，不需要查询数据库
        if (dtoList != null&&name==null) {
            return R.success(dtoList);
        }
        //3.如果不存在就查询数据库 并将查询到的菜品存入缓存当中
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //查询条件为起售状态的
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.like(name!=null,Dish::getName,name);
        //添加排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询得到除了口味之外的数据
        List<Dish> list = dishService.list(queryWrapper);
        //处理list集合
        dtoList = list.stream().map((item) -> {
            //1. 先将每一条数据拷贝给dishDto
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //2.根据id=dish_id  查询出一个菜品对应的所有的口味数据
            LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorQueryWrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            //根据分类ID查出分类名
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        //将结果返回给前端
        log.info("dishDto", dtoList);
        if (name==null){
            redisTemplate.opsForValue().set(key, dtoList, 60, TimeUnit.MINUTES);
        }
        return R.success(dtoList);
    }

    /**
     * 删除功能 删除分类表和菜品表
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> del(@RequestParam List<Long> ids) {
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 批量启售停售
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> sale(@PathVariable int status, @RequestParam List<Long> ids) {
        //update setmeal set status=#{status} where id in (ids)
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        List<Dish> list = dishService.list(queryWrapper);
        for (Dish d : list) {
            d.setStatus(status);
        }
        dishService.updateBatchById(list);
        return R.success("更改状态成功");
    }

}
